{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {},
   "outputs": [],
   "source": [
    "class ListNode:\n",
    "    def __init__(self, val=0, next=None):\n",
    "        self.val = val\n",
    "        self.next = next\n",
    "class Solution:\n",
    "    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:\n",
    "        v1 = ListNode(0)\n",
    "        res = v1\n",
    "        md = 0\n",
    "        while l1 or l2 or md:\n",
    "            value = (l1.val if l1 else 0) + (l2.val if l2 else 0) + md\n",
    "            res.next = ListNode(value % 10)\n",
    "            res = res.next\n",
    "            md = value // 10\n",
    "            \n",
    "            if l1:\n",
    "                l1 = l1.next\n",
    "            if l2:\n",
    "                l2 = l2.next\n",
    "        return v1.next       \n",
    "\n",
    "\n",
    "def encode(lst: list):\n",
    "    node = ListNode(0)\n",
    "    v1 = node\n",
    "    for each in lst:\n",
    "        v1.next = ListNode(each)\n",
    "        v1 = v1.next\n",
    "    return node.next\n",
    "\n",
    "\n",
    "def decode(node: ListNode):\n",
    "    values = []\n",
    "    while node:\n",
    "        values.append(node.val)\n",
    "        node = node.next\n",
    "    return values\n",
    "\n",
    "solution = Solution()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [],
   "source": [
    "l1 = ListNode(2, ListNode(4, ListNode(3)))\n",
    "l2 = ListNode(5, ListNode(6, ListNode(4)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 46,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "res = solution.addTwoNumbers(l1, l2)\n",
    "decode(res) == [7, 0, 8]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 47,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "decode(solution.addTwoNumbers(encode([9,9,9,9,9,9,9]), encode([9,9,9,9]))) == [8,9,9,9,0,0,0,1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
